package com.spring.boot.standard.admin.common.utils;

import com.google.gson.*;
import org.springframework.cglib.beans.BeanMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class GsonUtil {

	public static final Gson gson = new GsonBuilder().disableHtmlEscaping().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
	
	public static Gson getGson(){
		return gson;
	}

	/**
	 * 将map装换为javabean对象
	 *
	 * @param map
	 * @param bean
	 * @return
	 */
	public static <T> T mapToBean(Map<String, Object> map, T bean) {
		BeanMap beanMap = BeanMap.create(bean);
		beanMap.putAll(map);
		return bean;
	}

	/**
	 * json字符串转成list
	 *
	 * @param source
	 * @param cls
	 * @return
	 */
	public static <T> List<T> gsonToList(List<Map<String,Object>> source, Class<T> cls) {
		List<T> list = new ArrayList<>();
//		JsonParser parser = new JsonParser();
		for (Map<String,Object> map : source) {
			String jsonstr = gson.toJson(map);
			list.add(gson.fromJson(jsonstr,cls));
		}
		return list;
	}
	
}
